package com.ycsd.invest.order.business.workflowplugin;

import kd.bd.sbd.consts.OperationKeyConst;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.api.WorkflowElement;
import kd.bos.workflow.component.approvalrecord.CustomizeLink;
import kd.bos.workflow.component.approvalrecord.IApprovalRecordItem;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;
import kd.bos.workflow.engine.msg.info.MessageInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author yn
 * @Description 工作流插件
 * @Date 2025/6/25
 **/
public class TestWorkFlow implements IWorkflowPlugin {

    @Override
    public List<Long> calcUserIds(AgentExecution execution) {
        //单据的BusinessKey(单据id)
        String BusinessKey = execution.getBusinessKey();
        List<Long> currentApprover = execution.getCurrentApprover();//获取当前节点的审批人
        WorkflowElement<?> flowElement = execution.getCurrentFlowElement();//当前节点
        String id = flowElement.getId();//当前流程节点ID
        String name = flowElement.getName();//当前节点名称
        String number = flowElement.getNumber();//当前节点id
        String entityNumber = execution.getEntityNumber();//单据实体编码
        Long processDefinitionId = execution.getProcessDefinitionId();//获取流程定义ID
        Long processInstanceId = execution.getProcessInstanceId();//获取流程实例ID
        Long startUserId = execution.getStartUserId();//获取流程发起人
        //获取插件参数
        Map<String, Object> paramMap = execution.getCurrentWFPluginParams();
        Object amount = paramMap.get("amount");
        Object param = paramMap.get("param");
        Object vv = paramMap.get("vv");
        //获取流程变量，参数为String,此处为流程动态配置方案中"名称"的值,得到的是“默认值”的值
//        Object param = execution.getVariable("param");
//        Object vv = execution.getVariable("vv");
//        Object amount = execution.getVariable("amount");

        DynamicObject transientBill = execution.getTransientBill();
        //单据编号
        String billno = transientBill.getString("billno");

        //下面是自定义业务 把创建人设置为节点参与人
        currentApprover.add(startUserId);

        List<Long> userIds = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        numberList.add("ID-017004");
        numberList.add("ID-030013");
        numberList.add("ID-002007");
        numberList.add("ID-019001");
        QFilter filter = new QFilter("number", QCP.in, numberList);
        DynamicObjectCollection bosUser = QueryServiceHelper.query("bos_user", "id,name,number", new QFilter[]{filter});
        for (DynamicObject dynamicObject : bosUser) {
            userIds.add(dynamicObject.getLong("id"));
        }
        //返回值为 List<Long> 类型的数据。返回内容为参与人的id
        return userIds;

    }

    @Override
    public void notify(AgentExecution execution) {
        //单据的BusinessKey(业务ID)
        String businessKey = execution.getBusinessKey();
        String entityNumber = execution.getEntityNumber();
        //获取插件参数
        Map<String, Object> paramMap = execution.getCurrentWFPluginParams();
        Object amount = paramMap.get("amount");

        //创建消息
        MessageInfo messageInfo = new MessageInfo();
        ILocaleString iLocaleString = new LocaleString();
        iLocaleString.setLocaleValue("自定义消息标签");
        iLocaleString.setLocaleValue_zh_CN("自定义消息标签");
        iLocaleString.setLocaleValue_en("custom message tag");
        iLocaleString.setLocaleValue_zh_TW("tw 消息");
        messageInfo.setMessageTag(iLocaleString);
        messageInfo.setContentUrl("https://www.baidu.com");
        messageInfo.setContent("自定义消息主体");
        List<Long> userIds = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        numberList.add("ID-017004");
        numberList.add("ID-030013");
        numberList.add("ID-002007");
        numberList.add("ID-019001");
        QFilter filter = new QFilter("number", QCP.in, numberList);
        DynamicObjectCollection bosUser = QueryServiceHelper.query("bos_user", "id,name,number", new QFilter[]{filter});
        for (DynamicObject dyo : bosUser) {
            userIds.add(dyo.getLong("id"));
        }
        messageInfo.setUserIds(userIds);
        iLocaleString = new LocaleString();
        iLocaleString.setLocaleValue("自定义消息标题");
        iLocaleString.setLocaleValue_zh_CN("自定义消息标题");
        iLocaleString.setLocaleValue_en("custom message title");
        iLocaleString.setLocaleValue_zh_TW("tw 消息标题");
        messageInfo.setMessageTitle(iLocaleString);

        //发送通知
        MessageCenterServiceHelper.sendMessage(messageInfo);

        //流程结束通知
//        MessageInfo message = new MessageInfo();
//        message.setTitle("我要发一个消息。。。。。。。。。。。。。");
//        message.setContent("我要发一个消息。。。。。。。。。。。。的内容警告");
//        message.setUserIds(Collections.singletonList(execution.getStartUserId()));
//        message.setEntityNumber(null);
//        message.setBizDataId(null);
//        message.setOperation("modify");
//        message.setSenderId(0L);
//        message.setSendTime(new Date());
//        message.setSource("警告警告警告警告1");
//        message.setType(MessageInfo.TYPE_WARNING);
//        message.setTag("警告警告警告警告");
//        message.setContentUrl(null);
//        MessageCenterServiceHelper.sendMessage(message);

        //自动发起流程(创建一个单据 触发操作)
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject(entityNumber);
        dynamicObject.set("amount","10000");
        dynamicObject.set("billStatus","A");
        dynamicObject.set("valid", false);
        //获取单据类型
        DynamicObject type = BusinessDataServiceHelper.loadSingle("bos_billtype",
                new QFilter[]{new QFilter("number", QCP.equals, "ycsd_study_form")});
        dynamicObject.set("form_type",type);

        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(dynamicObject.getDataEntityType().getName(),
                dynamicObject, String.valueOf(RequestContext.get().getOrgId()));
        String number = CodeRuleServiceHelper.getNumber(codeRule, dynamicObject);
        dynamicObject.set("billNo",number);

//        OperationResult submitResult = OperationServiceHelper.executeOperate(OperationKeyConst.OP_SAVE, entityNumber,
//                new DynamicObject[]{dynamicObject}, OperateOption.create());
        OperationResult submitResult = OperationServiceHelper.executeOperate(OperationKeyConst.OP_SUBMIT, entityNumber,
                new DynamicObject[]{dynamicObject}, OperateOption.create());
        System.out.println(submitResult);
    }

    @Override
    public IApprovalRecordItem formatFlowRecord(IApprovalRecordItem item) {
        String activityName = item.getActivityName();//获取当前流程节点名称
        String assignee = item.getAssignee();//获取审批人姓名
        item.setActivityName("自定义当前流程节点：" + activityName);
        item.setAssignee("自定义当前审批人：" + assignee);
        List<CustomizeLink> links = new ArrayList<>();
        CustomizeLink link = new CustomizeLink();
        link.setText("百度");
        link.setUrl("https://www.baidu.com");
        links.add(link);
        item.setLinks(links);
        return item;
    }
}
